//
//  RHTableView.swift
//  JiuCheYue
//
//  Created by 刘表聪 on 2018/3/28.
//  Copyright © 2018年 xinzhen. All rights reserved.
//

import UIKit
import EmptyDataSet_Swift

class RHTableView: UITableView {
    
    var emptyText: String?
    
    var emptyImg: UIImage?
    
    var showEmptyView: Bool = false
    
    private var lastColor: UIColor?
    
    /**
     空态时，tableview背景色，默认白色
     */
    var emptyBackgroundColor: UIColor?
    
    override init(frame: CGRect, style: UITableViewStyle) {
        super.init(frame: frame, style: style)
        self.estimatedRowHeight = 44.0
        self.rowHeight = UITableViewAutomaticDimension
        self.separatorStyle = .none
        self.backgroundColor = RHAppSkinColor.sharedInstance.viewBackgroundColor
        self.emptyDataSetSource = self
        self.emptyDataSetDelegate = self
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.emptyDataSetSource = self
        self.emptyDataSetDelegate = self
    }
}

extension RHTableView: EmptyDataSetSource, EmptyDataSetDelegate {
    // MARK: - EmptyDataSetSource
    func customView(forEmptyDataSet scrollView: UIScrollView) -> UIView? {
        if(lastColor == nil) {
            lastColor = self.backgroundColor;
        }
        if (self.showEmptyView) {
            if(emptyBackgroundColor != nil) {
                self.backgroundColor = emptyBackgroundColor;
            } else {
                self.backgroundColor = RHAppSkinColor.sharedInstance.viewBackgroundColor
            }
        }
        let view = RHCustomEmptyView()
        view.updateViewImage(image: self.emptyImg, description: self.emptyText)
        return view
    }
    
    // MARK: - EmptyDataSetDelegate
    func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
        return true
    }
    
    func emptyDataSetShouldDisplay(_ scrollView: UIScrollView) -> Bool {
        return self.showEmptyView
    }
    
    func emptyDataSetDidAppear(_ scrollView: UIScrollView) {
        self.backgroundColor = lastColor;
    }
}
